const Core = require('@alicloud/pop-core');
const {config} = require('./config');
// console.log(config)
const publicIp = require('public-ip');
const moment = require('moment');


var CronJob = require('cron').CronJob;
new CronJob('*/2 * * * * *', function() {
  // console.log(1)
  const d = moment().format('YYYY-MM-DD HH:mm:ss')

  // let IP = "192.168.1.16"
  publicIp.v4().then(IP => {  
    // console.log(IP);
    // return

    let client = new Core({
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.accessSecret,
      endpoint: 'https://alidns.aliyuncs.com',
      apiVersion: '2015-01-09'
    });

    let getRecordsIDparams = {
      "RegionId": "cn-hangzhou",
      "SubDomain": config.domain
    }

    let requestOption = {
      method: 'POST'
    };

    client.request('DescribeSubDomainRecords', getRecordsIDparams, requestOption).then((result) => {
      // console.log(JSON.stringify(result));
      if(result.DomainRecords.Record[0].Value === IP){
        console.log(d + " 无需修改")
        return
      }

      let updateDomainparams = {
        "RegionId": "cn-hangzhou",
        "RecordId": result.DomainRecords.Record[0].RecordId,
        "RR": result.DomainRecords.Record[0].RR,
        "Type": "A",
        "Value": IP
      }

      client.request('UpdateDomainRecord', updateDomainparams, requestOption).then((result) => {
        console.log(d + "\n" + JSON.stringify(result));
      }, (ex) => {
        console.log(d + "\n" + ex);
      })

    }, (ex) => {
      console.log(d + "\n" + ex);
    })
  }, (err) => {
    console.log(d + "\n" + err)
  });
   
  // publicIp.v6().then(ip => {
  //     console.log(ip);
  //     //=> 'fe80::200:f8ff:fe21:67cf' 
  // });







}, null, true);












